import * as echarts from '../../ec-canvas/echarts';
//获取月份天数
var GetDays = require("../../fun/GetDays");
//获取处理过的当前日期
var formatDate = require("../../fun/formatDate");
//获取app实例
const app = getApp();

Page({
  data: {
    ec: {
      lazyLoad: true
    },
    bills: [{
      "_id": "28ee4e3e6041917f08ec33493e6b3a2e",
      "money": "700",
      "navItem": {
        "src": "../../images/gongche.png",
        "title": "交通",
        "type": "jt"
      },
      "payment": {
        "name": "支付宝",
        "type": "zfb"
      },
      "remarks": "对方过后",
      "today": "2021-03-06",
      "type": "sr",
      "userInfo": {
        "appId": "wxf45f0d0855948ffb",
        "openId": "oZ9od47UKWtVRRwFt7kiAl-FhXFk"
      }
    }, {
      "_id": "79550af26041921008600bbe2d080f38",
      "money": "123",
      "navItem": {
        "src": "../../images/zhufang.png",
        "title": "住房",
        "type": "zf"
      },
      "payment": {
        "name": "支付宝",
        "type": "zfb"
      },
      "remarks": "213",
      "today": "2021-03-06",
      "type": "sr",
      "userInfo": {
        "appId": "wxf45f0d0855948ffb",
        "openId": "oZ9od47UKWtVRRwFt7kiAl-FhXFk"
      }
    }, {
      "_id": "79550af26041942008607bd94abdc759",
      "money": "354",
      "navItem": {
        "src": "../../images/chuxing.png",
        "title": "出行",
        "type": "cx"
      },
      "payment": {
        "name": "微信",
        "type": "wx"
      },
      "remarks": "234",
      "today": "2021-03-06",
      "type": "zc",
      "userInfo": {
        "appId": "wxf45f0d0855948ffb",
        "openId": "oZ9od47UKWtVRRwFt7kiAl-FhXFk"
      }
    }, ],
    //收入支出选择
    lookType: 'zc',
    //收入
    income: [],
    // 支出
    expend: [],
    //日期选择
    currTime: '',
    copyCurrTime: '',
    //年月日选择
    nyrToggle: 'day',
    //收支总计算
    shouzhi: {
      income: 0.00,
      expend: 0.00
    },
    //颜色
    colors: ['#81D4FA', '#90caf9', '#80deea', '#80cbc4', '#42a5f5', '#26c6da', '#bbdefb', '#b3e5fc', '#b2ebf2'].sort((a) => Math.random() - 0.5)
    // colors:['#f06292','#ce93d8','#7986cb','#81d4fa','#26c6da','#4db6ac','#ffee58','#81c784','#ffe082','#ffccbc','#e57373'].sort((a)=>Math.random()-0.5)
  },

  onLoad() {
    //获取canvas元素
    this.echartsComponnet = this.selectComponent('#mychart-dom-graph');
    this.setData({
      currTime: formatDate(new Date()),
      copyCurrTime: formatDate(new Date()),
    })
  },
  onShow() {
    //获取数据并且渲染canvas
    this.getData();
  },
  onReady() {

  },
  //收入支出类型改变
  toggleType(e) {
    if (this.data.lookType == e.currentTarget.dataset.id) return;
    this.setData({
      lookType: e.currentTarget.dataset.id
    })
    this.setData({
      bills: this.data.lookType == "sr" ? this.data.income : this.data.expend
    })
    this.init_echarts();
  },
  //切换时间
  bindRegionChange(e) {
    let event = e.detail.value.split("-");
    let time = this.data.currTime.split("-")
    if (this.data.nyrToggle == "year") {
      time = `${event[0]}-${time[1]}-${time[2]}`;
    } else if (this.data.nyrToggle == "month") {
      time = `${event[0]}-${event[1]}-${time[2]}`;
    } else {
      time = `${event[0]}-${event[1]}-${event[2]}`;
    }
    this.setData({
      currTime: time,
      copyCurrTime: e.detail.value
    })
    // console.log(this.timeDispose(this.data.currTime));
    //切换月份从新获取数据
    this.getData();
  },
  //时间显示处理
  timeDispose(date) {
    let time = date.split("-")
    let start = date;
    let end = date
    if (this.data.nyrToggle == "year") {
      start = `${time[0]}-01-01`;
      end = `${time[0]}-12-31`;
    } else if (this.data.nyrToggle == "month") {
      start = `${time[0]}-${time[1]}-01`;
      end = `${GetDays(time[0],time[1])}`;
    }
    return {
      start,
      end
    }
  },
  //切换年月日
  toggleTime(e) {
    let time = e.currentTarget.dataset.time;
    if (this.data.nyrToggle == time) return;
    this.setData({
      nyrToggle: time,
    })
    let nyrType = this.timeDispose(this.data.currTime).start;
    if (this.data.nyrToggle == "year") {
      nyrType = nyrType.substring(0, 4);
    } else if (this.data.nyrToggle == "month") {
      nyrType = nyrType.substring(0, 7);
    }
    this.setData({
      copyCurrTime: nyrType
    })
    this.getData();
  },
  //获取数据
  getData() {
    // let date = this.data.currTime.split("-");
    //调用云函数
    wx.cloud.callFunction({
      name: "month_incomeAndexpend",
      data: {
        start: this.timeDispose(this.data.currTime).start,
        end: this.timeDispose(this.data.currTime).end
      }
    }).then(res => {
      console.log(res);
      //处理数据
      //收支总账
      let incomeTotal = 0;
      let expendTotal = 0;
      //去重数组
      let incomeArr = {};
      let expendArr = {};
      //每个条目总和数据
      let incomeList = [];
      let expendList = [];
      //数据去重并且将长度和钱加起来
      var inexpush = (item, inofexarr, type) => {
        if (!inofexarr[item.navItem.title] && item.type == type) {
          inofexarr[item.navItem.title]={
            ...item,
            name: item.navItem.title,
            value: item.money,
            length: 1,
            list: [item]
          };
        } else if (inofexarr[item.navItem.title] && item.type == type) {
          inofexarr[item.navItem.title].money = +inofexarr[item.navItem.title].money+ +item.money;
          inofexarr[item.navItem.title].length += 1;
          inofexarr[item.navItem.title].list.push(item);
        }
      }
      //循环，找出收入和支出的
      for (let j = 0; j < res.result.data.length; j++) {
        const item = res.result.data[j];
        //收支计算
        if (item.type == "sr") incomeTotal += +item.money;
        if (item.type == "zc") expendTotal += +item.money;
       //收入和支出列表计算  
        inexpush(item, expendArr, 'zc');
        inexpush(item, incomeArr, 'sr');
      }
      //数据处理完转成数组
      expendArr = Object.values(expendArr);
      incomeArr = Object.values(incomeArr);

      this.setData({
        shouzhi: {
          income: incomeTotal,
          expend: expendTotal
        },
      })
      //百分比处理
      let shouzhi = this.data.shouzhi.income;
      let percentage = (item, index) => {
        let percentage = (item.money / shouzhi * 100).toFixed(2) + "%";
        return {
          ...item,
          name:item.name+" "+percentage,
          percentage,
          color: this.data.colors[index]
        }
      }
      incomeArr = incomeArr.map(percentage);
      shouzhi = this.data.shouzhi.expend;
      expendArr = expendArr.map(percentage);

      // 设置最后处理完的数据
      this.setData({
        income:incomeArr,
        expend:expendArr,
        bills: this.data.lookType == 'sr' ? incomeArr : expendArr
      })
      // 调用渲染canvas函数
      this.init_echarts();
    });
  },
  //跳转到收支详情
  toDetailList(e) {
    wx.navigateTo({
      url: '../detailList/detailList',
      success(res) {
        res.eventChannel.emit("list", e.currentTarget.dataset.detail);
      }
    })
    console.log(e);
  },
  //初始化图表
  init_echarts() {
    this.echartsComponnet.init((canvas, width, height, dpr) => {
      // 初始化图表
      const Chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      });
      Chart.setOption(this.getOption());
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return Chart;
    });
  },
  getOption: function () {
    // 指定图表的配置项和数据
    var option = {
      tooltip: {
        trigger: 'item',
        // formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      legend: {
        bottom: 10,
        left: 'center',
        data: ['人情', '出行', '住房', '交通']
      },
      series: [{
        type: 'pie',
        radius: ['40%','65%'],
        center: ['50%', '50%'],
        selectedMode: 'single',
        color: this.data.colors,
        data: this.data.bills,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    }
    return option;
  },
});